/* ---------------------------------------------------------------------------------------------
 *
 *            Capital Alliance Software Confidential Proprietary
 *            (c) Copyright CAS 201{x}, All Rights Reserved
 *                          www.pekall.com
 *
 * ----------------------------------------------------------------------------------------------
 */

package com.android.music.adapter;

import java.util.Formatter;
import java.util.Locale;

import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.Context;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.CursorWrapper;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.provider.MediaStore;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.SimpleCursorTreeAdapter;
import android.widget.TextView;

import com.android.music.MusicApplication;
import com.android.music.R;
import com.android.music.util.Util;

public class ArtistListCursorAdapter extends SimpleCursorTreeAdapter {

    private AsyncQueryHandler mQueryHandler;

    private final BitmapDrawable mDefaultAlbumIcon;

    private Resources mResources;

    private Context mContext;

    public ArtistListCursorAdapter(Context context, Cursor cursor, int glayout, String[] gfrom,
            int[] gto, int clayout, String[] cfrom, int[] cto) {
        super(context, cursor, glayout, gfrom, gto, clayout, cfrom, cto);
        mContext = context;
        mQueryHandler = new QueryHandler(mContext.getContentResolver());
        Resources r = context.getResources();
        mDefaultAlbumIcon = (BitmapDrawable) r.getDrawable(R.drawable.albumart_mp_unknown_list);
        // no filter or dither, it's a lot faster and we can't tell the
        mDefaultAlbumIcon.setFilterBitmap(false);
        mDefaultAlbumIcon.setDither(false);
        mResources = context.getResources();
    }

    class ViewHolder {
        TextView line1;

        TextView line2;

        ImageView play_indicator;

        ImageView icon;
    }

    class QueryHandler extends AsyncQueryHandler {
        QueryHandler(ContentResolver res) {
            super(res);
        }

        @Override
        public void onQueryComplete(int token, Object cookie, Cursor cursor) {
            // mActivity.init(cursor);
        }
    }

    public AsyncQueryHandler getQueryHandler() {
        return mQueryHandler;
    }

    public View newGroupView(Context context, Cursor cursor, boolean isExpanded, ViewGroup parent) {

        View v = super.newGroupView(context, cursor, isExpanded, parent);
        ImageView iv = (ImageView) v.findViewById(R.id.icon);
        ViewGroup.LayoutParams p = iv.getLayoutParams();
        p.width = ViewGroup.LayoutParams.WRAP_CONTENT;
        p.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        ViewHolder vh = new ViewHolder();
        vh.line1 = (TextView) v.findViewById(R.id.line1);
        vh.line2 = (TextView) v.findViewById(R.id.line2);
        vh.play_indicator = (ImageView) v.findViewById(R.id.play_indicator);
        vh.icon = (ImageView) v.findViewById(R.id.icon);
        vh.icon.setPadding(0, 0, 1, 0);
        v.setTag(vh);
        return v;
    }

    @Override
    public View newChildView(Context context, Cursor cursor, boolean isLastChild, ViewGroup parent) {
        View v = super.newChildView(context, cursor, isLastChild, parent);
        ViewHolder vh = new ViewHolder();
        vh.line1 = (TextView) v.findViewById(R.id.line1);
        vh.line2 = (TextView) v.findViewById(R.id.line2);
        vh.play_indicator = (ImageView) v.findViewById(R.id.play_indicator);
        vh.icon = (ImageView) v.findViewById(R.id.icon);
        vh.icon.setBackgroundDrawable(mDefaultAlbumIcon);
        vh.icon.setPadding(0, 0, 1, 0);
        v.setTag(vh);
        return v;
    }

    public void bindGroupView(View view, Context context, Cursor cursor, boolean isexpanded) {

        ViewHolder vh = (ViewHolder) view.getTag();

        String artist = cursor.getString(1);
        String displayartist = artist;
        boolean unknown = artist == null || artist.equals(MediaStore.UNKNOWN_STRING);
        if (unknown) {
            displayartist = mContext.getString(R.string.unknown_artist_name);
        }
        vh.line1.setText(displayartist);

        int numalbums = cursor.getInt(2);
        int numsongs = cursor.getInt(3);

        String songs_albums = makeAlbumsLabel(context, numalbums, numsongs, unknown);

        vh.line2.setText(songs_albums);

        long currentartistid = 0;
        long artistid = cursor.getLong(0);
        if (currentartistid == artistid && !isexpanded) {
            vh.play_indicator.setImageDrawable(null);
        } else {
            vh.play_indicator.setImageDrawable(null);
        }
    }

    @Override
    public void bindChildView(View view, Context context, Cursor cursor, boolean islast) {

        ViewHolder vh = (ViewHolder) view.getTag();

        String name = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Albums.ALBUM));
        String displayname = name;
        boolean unknown = name == null || name.equals(MediaStore.UNKNOWN_STRING);
        if (unknown) {
            displayname = mContext.getString(R.string.unknown_artist_name);
        }
        vh.line1.setText(displayname);

        int numsongs = cursor.getInt(cursor
                .getColumnIndexOrThrow(MediaStore.Audio.Albums.NUMBER_OF_SONGS));
        int numartistsongs = cursor.getInt(cursor
                .getColumnIndexOrThrow(MediaStore.Audio.Albums.NUMBER_OF_SONGS_FOR_ARTIST));

        final StringBuilder builder = new StringBuilder();
        builder.delete(0, builder.length());
        if (unknown) {
            numsongs = numartistsongs;
        }

        if (numsongs == 1) {
            builder.append(context.getString(R.string.onesong));
        } else {
            if (numsongs == numartistsongs) {
                final Object[] args = new Object[1];
                ;
                args[0] = numsongs;
                builder.append(mResources.getQuantityString(R.plurals.Nsongs, numsongs, args));
            } else {
                final Object[] args = new Object[3];
                args[0] = numsongs;
                args[1] = numartistsongs;
                args[2] = cursor.getString(cursor
                        .getColumnIndexOrThrow(MediaStore.Audio.Artists.ARTIST));
                builder.append(mResources.getQuantityString(R.plurals.Nsongscomp, numsongs, args));
            }
        }
        vh.line2.setText(builder.toString());

        ImageView iv = vh.icon;
        // We don't actually need the path to the thumbnail file,
        // we just use it to see if there is album art or not
        String art = cursor.getString(cursor
                .getColumnIndexOrThrow(MediaStore.Audio.Albums.ALBUM_ART));
        if (unknown || art == null || art.length() == 0) {
            iv.setBackgroundDrawable(mDefaultAlbumIcon);
            iv.setImageDrawable(null);
        } else {
            long artIndex = cursor.getLong(0);
            Drawable d = MusicUtils.getCachedArtwork(context, artIndex, mDefaultAlbumIcon);
            iv.setImageDrawable(d);
        }

        long currentalbumid = 0;
        long aid = cursor.getLong(0);
        iv = vh.play_indicator;
        if (currentalbumid == aid) {
            iv.setImageDrawable(null);
        } else {
            iv.setImageDrawable(null);
        }
    }

    public Cursor getChildrenCursor(Cursor groupCursor) {
        long id = groupCursor.getLong(groupCursor
                .getColumnIndexOrThrow(MediaStore.Audio.Artists._ID));

        String[] cols = new String[] {
                MediaStore.Audio.Albums._ID, MediaStore.Audio.Albums.ALBUM,
                MediaStore.Audio.Albums.NUMBER_OF_SONGS,
                MediaStore.Audio.Albums.NUMBER_OF_SONGS_FOR_ARTIST,
                MediaStore.Audio.Albums.ALBUM_ART
        };
        Cursor c = query(MusicApplication.getInstance().getContext(),
                MediaStore.Audio.Artists.Albums.getContentUri("external", id), cols,
                Util.TIME_WHERE, null, MediaStore.Audio.Albums.DEFAULT_SORT_ORDER, 0);

        class MyCursorWrapper extends CursorWrapper {
            String mArtistName;

            int mMagicColumnIdx;

            MyCursorWrapper(Cursor c, String artist) {
                super(c);
                mArtistName = artist;
                if (mArtistName == null || mArtistName.equals(MediaStore.UNKNOWN_STRING)) {
                    mArtistName = mContext.getString(R.string.unknown_artist_name);
                }
                mMagicColumnIdx = c.getColumnCount();
            }

            @Override
            public String getString(int columnIndex) {
                if (columnIndex != mMagicColumnIdx) {
                    return super.getString(columnIndex);
                }
                return mArtistName;
            }

            @Override
            public int getColumnIndexOrThrow(String name) {
                if (MediaStore.Audio.Albums.ARTIST.equals(name)) {
                    return mMagicColumnIdx;
                }
                return super.getColumnIndexOrThrow(name);
            }

            @Override
            public String getColumnName(int idx) {
                if (idx != mMagicColumnIdx) {
                    return super.getColumnName(idx);
                }
                return MediaStore.Audio.Albums.ARTIST;
            }

            @Override
            public int getColumnCount() {
                return super.getColumnCount() + 1;
            }
        }

        return new MyCursorWrapper(c, groupCursor.getString(0));
    }

    private StringBuilder sFormatBuilder = new StringBuilder();

    private Formatter sFormatter = new Formatter(sFormatBuilder, Locale.getDefault());

    public String makeAlbumsLabel(Context context, int numalbums, int numsongs, boolean isUnknown) {

        StringBuilder songs_albums = new StringBuilder();

        Resources r = context.getResources();
        if (isUnknown) {
            if (numsongs == 1) {
                songs_albums.append(R.string.onesong);
            } else {
                String f = r.getQuantityText(R.plurals.Nsongs, numsongs).toString();
                sFormatBuilder.setLength(0);
                sFormatter.format(f, Integer.valueOf(numsongs));
                songs_albums.append(sFormatBuilder);
            }
        } else {
            String f = r.getQuantityText(R.plurals.Nalbums, numalbums).toString();
            sFormatBuilder.setLength(0);
            sFormatter.format(f, Integer.valueOf(numalbums));
            songs_albums.append(sFormatBuilder);
            songs_albums.append(",");
        }
        return songs_albums.toString();
    }

    public Cursor query(Context context, Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder, int limit) {

        try {
            ContentResolver resolver = context.getContentResolver();
            if (resolver == null) {
                return null;
            }
            if (limit > 0) {
                uri = uri.buildUpon().appendQueryParameter("limit", "" + limit).build();
            }
            return resolver.query(uri, projection, selection, selectionArgs, sortOrder);
        } catch (UnsupportedOperationException ex) {
            return null;
        }

    }

}
